namespace Tycho.Parser.Peg {
    public class StatementDelimiterProduction : Production {
        public readonly IProduction IndentationTerminal;

        public StatementDelimiterProduction () {
            IndentationTerminal = IndentationProduction.CreateTerminal ();
            Name = ";";
            ErrorInformation = new KeywordErrorInformation (";");
        }

        public static Terminal CreateTerminal () {
            return new Terminal (new StatementDelimiterProduction ());
        }

        protected override ParseResult ReallyParse (char[] source, int index, ParseContext context, string sourceString, ParseEnvironment parseEnvironment) {
            if (source[index] == ';') {
                return new ParseResult (index + 1, new KeywordTerm (";", parseEnvironment.SourceFileInformation.CreateSourceInformation (index, 1)), context);
            }

            var indentResult = IndentationTerminal.Parse (source, index, context, sourceString, parseEnvironment);
            
            if (indentResult != null) {
                var indentationTerm = (IndentationTerm) indentResult.Term;
                if (indentationTerm.GetIndentation (context.LastIndent) == Indentation.StatementDelimiter || context.BracketDepth > 0) {
                    SourceInformation sinfo = parseEnvironment.SourceFileInformation.CreateSourceInformation (index, indentResult.Index - index);
                    return new ParseResult (indentResult.Index, new KeywordTerm (";", sinfo), indentResult.Context);
                }
            }

            return null;
        }
    }
}